package com.gradledemo.common.shiro;

/*
 * Copyright (c) 2010-2015 LiZaoNet Inc. (http://www.lizaonet.com).
 * license: http://www.lizaonet.com
 */

import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by Charles.Tan on 2015-01-29.
 */
public class VelocityToolboxView20 extends VelocityLayoutView {
    @Override
    protected Context createVelocityContext(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        ViewToolContext viewToolContext = new ViewToolContext(getVelocityEngine(), request, response, getServletContext());

        viewToolContext.putAll(model);

        if (this.getToolboxConfigLocation() != null) {
            ToolManager toolManager = new ToolManager();
            toolManager.setVelocityEngine(getVelocityEngine());
            toolManager.configure(getServletContext().getRealPath(getToolboxConfigLocation()));

            if (toolManager.getToolboxFactory().hasTools(Scope.REQUEST)) {
                viewToolContext.addToolbox(toolManager.getToolboxFactory().createToolbox(Scope.REQUEST));
            }
            if (toolManager.getToolboxFactory().hasTools(Scope.APPLICATION)) {
                viewToolContext.addToolbox(toolManager.getToolboxFactory().createToolbox(Scope.APPLICATION));
            }
            if (toolManager.getToolboxFactory().hasTools(Scope.SESSION)) {
                viewToolContext.addToolbox(toolManager.getToolboxFactory().createToolbox(Scope.SESSION));
            }

        }
        return viewToolContext;
    }
}
